<?php

class Login extends CI_Controller{

	var $prev_site;

	function __construct(){
		parent::__construct();

		$this->lang->load('openid', 'english');
		$this->load->library('openid');
		$this->load->helper('url');

		$this->load->model('login_model');

		$this->load->model('menu_model');
		$view_content['menuitems'] = $this->menu_model->menuitems;
	}

	function index(){
		echo 'this is login.php';
	}

	//Verify the openid url that the user is trying to login with.
	function verify(){


		// Before we check if the username is in fact an OpenID, we must secure
		// the variable. OpenID refers to the url as $user_id, so be sure to assign
		// the value of the inputted openid to $user_id. Here is have used
		// $this->username but this might change on your system.

		$this->prev_site = $this->input->server('HTTP_REFERER', TRUE);
		//echo $this->prev_site;

		$user_id = trim($this->input->post('openid_identifier'));
		$user_id = htmlspecialchars($user_id);

		if(!$user_id){
			redirect($this->prev_site, 'location');
		}
		echo 'Verifying...';

		// Load the neccessary OpenID libraries as shown by the example.
		$this->lang->load('openid', 'english');
		$this->load->library('openid');
		$this->config->load('openid');
		$req = $this->config->item('openid_required');
		$opt = $this->config->item('openid_optional');
		$policy = site_url($this->config->item('openid_policy'));
		$request_to = site_url($this->config->item('openid_request_to'));

		$this->openid->set_request_to($request_to);
		$this->openid->set_trust_root(base_url());
		$this->openid->set_args(null);
		$this->openid->set_sreg(true, $req, $opt, $policy);
		$pape_policy_uris = array();
		$this->openid->set_pape(true, $pape_policy_uris);
		$error = $this->openid->authenticate($user_id);
		if($error){

			$this->load->model('menu_model');
			$view_content['menuitems'] = $this->menu_model->menuitems;

			$view_content['error'] = $error;
			$view_content['main_content'] =  'login_fail';
			$view_content['selected_item'] = $this->menu_model->getMenuItem('home');
			$this->load->view('includes/template', $view_content);

		}
	}

	//Authenticate the openid url.
	function check(){
		$this->lang->load('openid', 'english');
		$this->load->library('openid');
		$this->config->load('openid');
		$request_to = site_url($this->config->item('openid_request_to'));

		$this->openid->set_request_to($request_to);
		$response = $this->openid->getResponse();

		switch ($response->status)
		{
			// This is probably the most important bit of the check. The switch case
			// statements. They're pretty obvious as to what they do. All the same,
			// I have bolded part of their names for the hard of thinking ... haha.
			case Auth_OpenID_CANCEL:
				//$data['msg'] = $this->lang->line('openid_cancel');
				redirect(base_url(), 'location');
				break;
			case Auth_OpenID_FAILURE:
				$data['error'] = $this->_set_message('openid_failure', $response->message);

				$view_content['error'] = $data['error'];
				$view_content['main_content'] =  'login_fail';
				$view_content['selected_item'] = $this->menu_model->getMenuItem('home');
				$this->load->view('includes/template', $view_content);
				break;
			case Auth_OpenID_SUCCESS:
				$openid = $response->getDisplayIdentifier();
				$esc_identity = htmlspecialchars($openid, ENT_QUOTES);

				$data['success'] = $this->_set_message('openid_success', array($esc_identity, $esc_identity), array('%s','%t'));

				if ($response->endpoint->canonicalID) {
					$data['success'] .= $this->_set_message('openid_canonical', $response->endpoint->canonicalID);
				}

				$sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
				$sreg = $sreg_resp->contents();

				foreach ($sreg as $key => $value)
				{
					$$key = $value;
					$data['success'] .= $this->_set_message('openid_content', array($key, $value), array('%s','%t'));
				}

				$pape_resp = Auth_OpenID_PAPE_Response::fromSuccessResponse($response);

				if ($pape_resp)
				{
					if ($pape_resp->auth_policies)
					{
						$data['success'] .= $this->lang->line('openid_pape_policies_affected');

						foreach ($pape_resp->auth_policies as $uri)
						{
							$data['success'] .= "<li><tt>$uri</tt></li>";
						}

						$data['success'] .= "</ul>";
					}
					else
					{
						$data['success'] .= $this->lang->line('openid_pape_not_affected');
					}

					if ($pape_resp->auth_age)
					{
						$data['success'] .= $this->_set_message('openid_auth_age', $pape_resp->auth_age);
					}

					if ($pape_resp->nist_auth_level)
					{
						$data['success'] .= $this->_set_message('openid_nist_level', $pape_resp->nist_auth_level);
					}
				}
				else
				{
					$data['success'] .= $this->lang->line('openid_pape_noresponse');
				}

				// At this point, we have authenticated the OpenID COMPLETELY, and
				// we have also grabbed whatever information we have requested. For
				// example:

				// $nickname is the nickname we have grabbed in openid_required. It
				// may or may not be empty.
				/*echo $nickname;
				 if ( !$nickname )
				 {
					// If $nickname is blank, and we require it for our system, we
					// should now execute some code that will ask them to fill out a
					// nickname. This is for you to figure out. It will probably
					// loading a separate view or redirecting.
					}
					else
					{
					// If we have all the required information we need, we can move on
					// to section (C) in the flow chart.
					}

					// Remember we had to store the openid URL in a new table so we can
					// bind them to users? $esc_identity is the variable you need. Note:
					// it is canonicalised - that means that the format is standardized
					// such as foo.bar.com becomes http://foo.bar.com/.
					echo $esc_identity;*/


				if($this->login_model->isRegistered($esc_identity)){
					$user_id = $this->user_model->getUserId($esc_identity);
					$this->session->set_userdata(array(
											'username'=>$nickname, 
											'email'=>$email, 
											'userid'=>$user_id,
											'logged_in'=>TRUE));
					//echo "WUUUUUUTTTTT    ".$this->prev_site;
					redirect($this->prev_site, 'location');
				}
				else{
					$view_content['openid_url'] = $esc_identity;
					if(!isset($nickname)){
						$nickname = '';
					}
					if(!isset($email)){
						$email = '';
					}
					$view_content['username'] = $nickname;
					$view_content['email'] = $email;
						
					$this->load->model('menu_model');
					$view_content['menuitems'] = $this->menu_model->menuitems;
					$view_content['main_content'] =  'register_user_view';
					$view_content['selected_item'] = $this->menu_model->getMenuItem('home');
					$this->load->view('includes/template', $view_content);
				}

					
				break;
		}

		$data['pape_policy_uris'] = array(
		PAPE_AUTH_MULTI_FACTOR_PHYSICAL,
		PAPE_AUTH_MULTI_FACTOR,
		PAPE_AUTH_PHISHING_RESISTANT
		);
		// I have commented out the load->view because we want to use our own
		// view. See flow chart. You will have to edit it so that it does what
		// YOU want it to do. All I am doing is showing you how to set up a
		// basic structure.



		//$this->load->view('view_openid', $data);
	}

	//Register a new user in the database.
	function registerUser(){
		$this->load->library('form_validation');

		//The form rules
		$this->form_validation->set_rules('openid_identifier', 'OpenID url', 'required|xss_clean');
		$this->form_validation->set_rules('username', 'Username', 'required|xss_clean');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean');

		if($this->form_validation->run() == FALSE){
			$data;
			$this->load->model('menu_model');
			$this->data['menuitems'] = $this->menu_model->menuitems;

			$this->data['openid_url'] = $this->input->post('openid_identifier');
			$this->data['username'] = $this->input->post('username');
			$this->data['email'] = $this->input->post('email');

			$this->data['main_content'] =  'register_user_view';
			$this->data['selected_item'] = $this->menu_model->getMenuItem('home');
			$this->load->view('includes/template', $this->data);
		}else{
			$openid_url = trim($this->input->post('openid_identifier'));
			$openid_url = htmlspecialchars($openid_url);

			$username = trim($this->input->post('username'));

			$email = trim($this->input->post('email'));

			$this->login_model->registerUser($openid_url, $username, $email);

			//$this->verify($openid_url);
			$user_id = $this->user_model->getUserId($openid_url);
			$this->session->set_userdata(array('username'=>$username, 'email'=>$email, 'userid'=>$user_id, 'logged_in'=>TRUE));
			redirect(base_url(), 'location');
		}
	}

	function _set_message($msg, $val = '', $sub = '%s')
	{
		return str_replace($sub, $val, $this->lang->line($msg));
		/*if ($error)
		 {
			//exit;
			header( "Location:". site_url('/login/verify/0')) ;
			}*/

	}


	//Logout the user and destroys the session
	function logout(){
		$this->session->sess_destroy();
		$this->prev_site = $this->input->server('HTTP_REFERER', TRUE);
		redirect($this->prev_site, 'location');
	}
}